from flask import render_template,redirect,url_for,session, flash, request
from flask_login import login_required, current_user
#from flaskext.uploads import UploadSet, IMAGES
from bson.dbref import DBRef

from controller import app
from lib.form import Form

from dao.subject import SubjectDao
from dao.comment import CommentDao

from service.comment import CommentForm, CommentService
import json

class CommentsForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)




@app.route('/manage_comments')
@app.route('/manage_comments', methods=['GET','POST'])
@login_required
def manage_comments():
    form = CommentForm()
    session['errors_json'] = ''
    if form.is_submitted():
        if form.has_error():
            session['errors_json'] = json.dumps(form.errors)
            return redirect(url_for('display_comments'))#errors_json=json.dumps(form.errors)))
        else:
            service = CommentService()
            service.submit_comment(form)
            return redirect(url_for('display_comments'))
    else:
        return redirect(url_for('display_comments'))

@app.route('/display_comments')
@login_required
def display_comments():
    #return render_template("add_comment-v1.html", comments=None)

    if session['errors_json'] == '':
        errors = []
    else:
        errors = session['errors_json']
    
    service = CommentService()
    user = service.get_current_user()
    _comments = service.get_comment_list()
    return render_template("main_dashboard.html", errors_json=errors, comments=_comments, user=user)
    
@app.route("/delete_comments", methods=["GET", "POST"])
@login_required
def delete_comments():
    comment_dao = CommentDao()
    
    form = CommentsForm()
    ids = form.request.form.getlist('selected')
    for _id in ids:
        comment = comment_dao.filter_first(id=int(_id))
        comment_dao.remove_from_db(comment)
        
    return render_template("manage_comments.html", comments=comment_dao.all())            
